window.yt = {
	www: {
		watch: {
			player: {
				seekTo: function (time) {
					console.log("nTube: Seeking to " + time + ".");
					if (window.mainPlayer) {
						window.mainPlayer.seek(time);
					} else {
						var pp = document.getElementById("__video_player");
						if (pp.tagName === "DIV") {
							pp = pp.children[0];
						}
						pp.currentTime = time;
					}
				},
			},
		},
	},
};
window.ui = {
	initPlyr: function (dashObject) {
		console.debug("initPlyr::Object called with dashObject: ", dashObject);
		if (window.plyrObject) {
			return;
		} else {
			loadScripts([libWeb.ESCompat.checkIfCompatible(6) ? "resources/plyr/plyr.js" : "resources/plyr/plyr.polyfilled.js"], function () {
				var vjs_css = document.createElement("link");
				vjs_css.href = "resources/plyr/plyr.css";
				vjs_css.rel = "stylesheet";
				vjs_css.type = "text/css";
				vjs_css.media = "all";
				document.head.appendChild(vjs_css);
				const player = new Plyr(document.querySelector("video"), {
					captions: {
						active: true,
						update: true,
					},
					invertTime: false,
					disableContextMenu: false,
					dashObject: dashObject,
				});
				window.plyrObject = player;
				player.on("ready", function (e) {
					document.getElementById("__video_player").playbackRate = 1;
					const _o = document.querySelector("#__video_div_element").children[0];
					_o.addEventListener("webkitfullscreenchange", function () {
						if (document.webkitFullscreenElement !== null) {
							document.getElementById("__video_player").style.height = "100%";
						} else {
							document.getElementById("__video_player").style.height = "84vh";
						}
					});
					_o.addEventListener("fullscreenchange", function () {
						if (document.fullscreenElement !== null) {
							document.getElementById("__video_player").style.height = "100%";
						} else {
							document.getElementById("__video_player").style.height = "84vh";
						}
					});
					_o.addEventListener("mozfullscreenchange", function () {
						if (document.fullscreenElement !== null) {
							document.getElementById("__video_player").style.height = "100%";
						} else {
							document.getElementById("__video_player").style.height = "84vh";
						}
					});
				});
			});
		}
	},
};
window.playback = {
	methods: {
		initDashJS: function (dashPayload, DASH_JS_EXPERIMENTAL_OPTIONS, callback) {
			const payload_url = "/b64_dec?td=" + dashPayload + "&dashMime";
			if (window.playback["dash"] !== null && window.playback["dash"] !== undefined) {
				window.playback.dash.attachSource(payload_url);
				callback();
			} else {
				loadScripts(["/resources/dash.js"], function () {
					var settings = {
						settings: {
							streaming: {
								fastSwitchEnabled: !window.isIE11,
								stableBufferTime: 15,
								bufferToKeep: getBufferSize(),
								bufferTimeAtTopQualityLongForm: getHQBufferSize(),
								scheduleWhilePaused: false,
								retryIntervals: {
									InitializationSegment: 133,
									IndexSegment: 133,
									MediaSegment: 133,
									BitstreamSwitchingSegment: 133,
									other: 133,
								},
							},
						},
					};
					if (DASH_JS_EXPERIMENTAL_OPTIONS) {
						console.debug("[ndashPlayer] Loading experimental options.");
						settings = mergeJSON(settings, {
							settings: {
								streaming: {
									abr: {
										ABRStrategy: "abrBola",
										useBufferOccupancyABR: true,
										bandwidthSafetyFactor: 0.95,
									},
								},
							},
						});
					}
					const player = dashjs.MediaPlayer().create(settings);
					window.playback.dash = player;
					window.playback.method = "dash";
					player.initialize(id("__video_player"), payload_url, true);
					callback();
				});
			}
		},
		initShaka: function (dashPayload) {},
	},
};
function loadVideo(videoID) {
	if (videoID === null || videoID === undefined) return;
	if (videoID.length === 0) throw new Error("videoID is empty!");
	var extra = "";
	if (videoID.indexOf("&list=") > -1) extra += "&list=" + getQueryVariableString(videoID, "list");
	if (videoID.indexOf("?v=") > -1) videoID = getQueryVariableString(videoID, "v");
	show(id("loading-indicator"));
	fadein(id("loading-indicator"));
	run_promise(function () {
		function allowAV1() {
			if (av1Action === "def") {
				return supportsAV1playback() || getQueryVariable("av1") !== null;
			} else {
				return av1Action === "fon";
			}
		}
		const VIDEO_ID = videoID;
		var allowWebM = supportsVideoType("vp9") === "probably";
		var av1Action = "def";
		var remove30FPSVideos = true;
		var DASH_JS_ENABLE_QUALITY_ENFORCEMENT = false;
		var USE_10_BIT_CONTENT = false;
		var DASH_JS_EXPERIMENTAL_OPTIONS = getQueryVariable("dashjs_legacy_options") === null;
		var PLAYBACK_ENGINE = "plyr-dash";
		var EMULATE_MSE_MISSING = getQueryVariable("emu_no_mse") !== null;
		var USE_PLYR_AS_FALLBACK = EMULATE_MSE_MISSING;
		var ENABLE_EQUALIZER = false;
		var jxr = {
			next_api_version: 3,
			videoID: VIDEO_ID,
			enableAV1: allowAV1(),
			enableWebM: allowWebM || getQueryVariable("allowWebM") !== null,
			isBitChute: getQueryVariable("bc") !== null,
			enableDashJS: PLAYBACK_ENGINE === "videojs-dash" || PLAYBACK_ENGINE === "dash.js" || PLAYBACK_ENGINE === "plyr-dash" || PLAYBACK_ENGINE === "shaka" || PLAYBACK_ENGINE === "shaka+ui",
			dashJSUseCompression: false,
			dashJSAllowCaching: true,
			preferredQuality: -1,
			dashJS_force60FPS: remove30FPSVideos || getQueryVariable("mpdForce60") !== null,
			enableHDR: USE_10_BIT_CONTENT || getQueryVariable("enableHDR") !== null,
			clar: getQueryVariable("clar") !== null,
			telemetry: {
				h264: supportsVideoType("h264") === "probably",
				vp9: supportsVideoType("vp9") === "probably",
				av1: supportsAV1playback(),
				client: nTube.nTubeUtils.getBrowserVersion(),
				frontend: "ntube-next-ui",
			},
		};
		request(
			"/api/get_video?v=" + VIDEO_ID + extra,
			JSON.stringify(jxr),
			function (error) {
				console.error("[nTubeNX::loadVideo] :/\n", error);
				fadeout(id("nplayer_loading"), function () {
					hide(id("nplayer_loading"));
				});
			},
			function (_data) {
				const data = JSON.parse(_data);
				processVideoMetadata(data, PLAYBACK_ENGINE, DASH_JS_EXPERIMENTAL_OPTIONS, VIDEO_ID);
			}
		);
	});
}

function processVideoMetadata(data, PLAYBACK_ENGINE, DASH_JS_EXPERIMENTAL_OPTIONS, VIDEO_ID) {
	const jsonObject = data;
	window.jsonObject = data;
	function metadata(error_id) {
		if (error_id !== null && error_id !== undefined) {
			console.error("[nTubeNX::metadata_error] Error: " + error_id);
			id("nplayer-ui-main-div").style.display = "none";
			id("nplayer-ui-main-div").style.visibility = "hidden";
			id("error_div").style.display = "";
			id("error_div").style.visibility = "";
			document.title = ":/ - nTube.";
		} else {
			if (jsonObject["metadata"] && jsonObject["metadata"]["title"]) {
				document.title = jsonObject["metadata"]["title"] + " - nTube.";
				id("video_title").innerHTML = jsonObject["metadata"]["title"];
			}
			if (jsonObject["metadata"] && jsonObject["metadata"]["author"]) {
				id("channel_title").innerHTML = jsonObject["metadata"]["author"];
			}
			if (jsonObject["metadata"] && jsonObject["metadata"]["description"]) {
				id("description_content").innerHTML = jsonObject["metadata"]["description"];
			}
			if (jsonObject["metadata"] && jsonObject["metadata"]["views"]) {
				if (jsonObject["metadata"]["views"] === -1) {
					id("view_count_string").innerHTML = "N/A";
				} else {
					id("view_count_string").innerHTML = numberWithCommas(jsonObject["metadata"]["views"]);
				}
			}
			if (jsonObject["metadata"] && jsonObject["metadata"]["duration"]) {
				if (jsonObject["metadata"]["duration"] <= -1) {
					id("video_duration").innerHTML = "N/A";
				} else {
					id("video_duration").innerHTML = seconds2time(jsonObject["metadata"]["duration"]);
				}
			}
			if (window.nTube1Globals) {
				window.nTube1Globals.loadMediaMetadata(VIDEO_ID, jsonObject, "ntube.desktop");
			}
		}
	}
	function video() {
		if (jsonObject["videos"] && jsonObject["videos"]["muxedPayload"]) {
			if (PLAYBACK_ENGINE === "plyr-dash" || PLAYBACK_ENGINE === "dash.js") {
				window.playback.methods.initDashJS(jsonObject["videos"]["muxedPayload"], DASH_JS_EXPERIMENTAL_OPTIONS, function () {
					if (PLAYBACK_ENGINE === "plyr-dash") {
						window.ui.initPlyr(window.playback.dash);
					}
				});
			}
		}
		fadeout(id("loading-indicator"), function () {
			hide(id("loading-indicator"));
		});
	}
	function related() {
		/*
            <!--<div style="display: table;">
                <img style="width: 160px; height: 90px; vertical-align: middle; display: table-row;" src="https://i.ytimg.com/vi/PYZrO04MJS4/hqdefault.jpg">
                <div style="vertical-align: middle; display: table-cell; padding-left: 5px; padding-right: 5px;">
                    <h3 style="vertical-align: middle; margin: 0px auto;">youre waifu</h3>
                    <p style="vertical-align: bottom; margin: 5px 0px; font-size: small;">is trash &centerdot; because I &centerdot; said so.</p>
                </div>
            </div>-->
        */
		id("related_div").innerHTML = "";
		if (jsonObject["related"] && jsonObject["related"].length > 0) {
			const rdiv = id("related_div");
			for (var i = 0; i < jsonObject["related"].length; i++) {
				const data = jsonObject["related"][i];
				var videoDiv = document.createElement("div");
				videoDiv.style.display = "table";
				videoDiv.style.marginBottom = "5px";
				const image = document.createElement("img");
				image.style.verticalAlign = "middle";
				image.style.display = "table-row";
				image.style.width = "160px";
				image.style.height = "90px";
				image.loading = "lazy";
				image.decoding = "async";
				if (data["ani_thumb"]) {
					const im = data.imgURL;
					const ia = data.ani_thumb;
					image.src = im;
					image.onmouseover = function () {
						image.src = ia;
					};
					image.onmouseout = function () {
						image.src = im;
					};
				} else {
					image.src = data.imgURL;
				}
				image.onclick = function () {
					loadVideo(data["link"]);
					if (window.history && window.history.pushState) {
						try {
							history.pushState({}, null, data["link"].replace("/watch?", "/watch_next?"));
						} catch (E) {
							console.error("Failed to push history.", E);
						}
					}
				};
				videoDiv.appendChild(image);
				var contentDiv = document.createElement("div");
				contentDiv.style.verticalAlign = "middle";
				contentDiv.style.display = "table-cell";
				contentDiv.style.paddingLeft = "5px";
				contentDiv.style.paddingRight = "5px";
				var videoTitle = document.createElement("h3");
				videoTitle.style.verticalAlign = "middle";
				videoTitle.style.margin = "0px auto";
				videoTitle.innerHTML = data.title;
				contentDiv.appendChild(videoTitle);
				var videoDescription = document.createElement("p");
				videoDescription.style.verticalAlign = "bottom";
				videoDescription.style.margin = "5px 0px";
				videoDescription.style.fontSize = "small";
				videoDescription.innerHTML = data.channel;
				if (data.isPlaylist) {
					videoDescription.innerHTML += " &centerdot; PLAYLIST";
				} else {
					videoDescription.innerHTML += " &centerdot; ";
					videoDescription.innerHTML += seconds2time(data.duration);
					if (data.views && data.views !== -1) {
						videoDescription.innerHTML += " &centerdot; " + numberWithCommas(data.views);
					}
				}
				if (data["isUpNext"]) {
					videoDescription.innerHTML += " &centerdot; Up Next.";
					videoDiv.setAttribute("is-upnext", "true");
				}
				contentDiv.appendChild(videoDescription);
				videoDiv.appendChild(contentDiv);
				rdiv.appendChild(videoDiv);
			}
		}
	}
	function captions() {
		id("__video_player").innerHTML = "";
		if (jsonObject["captions"] && jsonObject["captions"].length > 0) {
			if (PLAYBACK_ENGINE === "shaka" || PLAYBACK_ENGINE === "shaka+ui") {
				// TODO
			} else {
				for (var i = 0; i < jsonObject["captions"].length; i++) {
					var caption = jsonObject["captions"][i];
					var track = document.createElement("track");
					track.kind = "captions";
					track.label = caption.text;
					track.srclang = caption.code;
					track.src = caption.url;
					id("__video_player").appendChild(track);
				}
			}
		}
	}
	run_task(function () {
		captions();
	}, nTube.PromisePriority.BACKGROUND_TASK);
	run_task(function () {
		metadata(jsonObject["error_id"]);
	}, nTube.PromisePriority.VISIBLE_TASK);
	run_task(function () {
		related();
	}, nTube.PromisePriority.BACKGROUND_TASK);
	run_task(function () {
		video();
	}, nTube.PromisePriority.BLOCKING_TASK);
}
run_promise(function () {
	id("extras-tab-header-exit-button").onclick = function () {
		fadeout(id("extras-tab-full"), function () {
			hide(id("extras-tab-full"));
		});
	};
});
